#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2024 SteamFork (https://github.com/SteamFork)

set -e
set -x

if [ -f "${HOME}/.SteamFork/options" ]
then
 source "${HOME}/.SteamFork/options"
fi

for KEY in SIGNKEY
do
  if [ -z "${!KEY}" ]
  then
    echo "Export ${KEY} before using this script."
    exit 1
  fi
done

echo "Cache key" | gpg --sign -o /dev/null
if [ ! "$?" = 0 ]
then
  echo "Unable to cache signing key, quitting..."
fi

while [[ $# -ge 2 ]]
do
  KEY="$1"
  case ${KEY} in
      --branch)
      STEAMOS_VERSION="$2"
      shift # past argument
      shift # past value
      ;;
      --repo)
      PKGSOURCE="$2"
      shift # past argument
      shift # past value
      ;;
      --*)
        echo "Unknown option ${KEY}"
	exit 1
      ;;
  esac
done

if [ -z "${PKGSOURCE}" ]
then
  PKGSOURCE="local"
fi

if [ -z "${OS_ARCH}" ]
then
	OS_ARCH=$(uname -m)
fi

BUILDUSER=${USER}
WORK_DIR="${WORK_DIR}/packages/${1}"
REPO_DIR="${REPO_DIR}/${STEAMOS_VERSION}/os/${OS_ARCH}"

sudo steamos-readonly disable
sudo rm -rf /var/lib/pacman/db.lck ${WORK_DIR}
sudo pacman -Sy ||:

sudo mkdir -p ${WORK_DIR} ${REPO_DIR} 2>/dev/null
sudo chown ${BUILDUSER}:${BUILDUSER} ${WORK_DIR} ${REPO_DIR}

case ${PKGSOURCE} in
  aur)
    git clone --depth=1 https://aur.archlinux.org/${1}.git ${WORK_DIR}
  ;;
  sf)
    git clone --depth=1 git@github.com:steamfork/${1}.git ${WORK_DIR}
  ;;
  local)
    if [ -d "$(pwd)/PKGBUILD/${1}" ]
    then
      cp -r "$(pwd)/PKGBUILD/${1}/"* ${WORK_DIR}
    else
      echo "No local package, don't know what to do."
      exit 1
    fi
  ;;
  *)
    echo "scripts/mkpackage type repo"
    exit 1
  ;;
esac

source ${WORK_DIR}/PKGBUILD

for STALE_PACKAGE in ${pkgbase} ${pkgbase}-debug ${pkgname[@]} ${pkgname[@]}-debug
do
  rm -f ${REPO_DIR}/${STALE_PACKAGE}-[0-9]*
done

PIKAUR_CMD="PKGDEST=${REPO_DIR} pikaur --noconfirm --rebuild --build-gpgdir /etc/pacman.d/gnupg -S -P ${WORK_DIR}/PKGBUILD"
PIKAUR_RUN=(bash -c "${PIKAUR_CMD}")
"${PIKAUR_RUN[@]}"
# if aur package is not successfully built, exit
if [ $? -ne 0 ]; then
    echo "Build failed. Stopping..."
    exit -1
fi
# remove any epoch (:) in name, replace with -- since not allowed in artifacts
find ${REPO_DIR}/*.pkg.tar* -type f -name '*:*' -execdir bash -c 'mv "$1" "${1//:/--}"' bash {} \;

# Sign packages.
for PKG in ${pkgbase} ${pkgbase}-debug ${pkgname[@]}
do
  for TOSIGN in ${REPO_DIR}/${PKG}-${pkgver}*tar.zst
  do
    if [ -f "${TOSIGN}" ]
    then
      gpg --yes --detach-sign --use-agent --no-armor ${TOSIGN}
    fi
  done
done
cd ${REPO_DIR}
repo-add --verify --sign -k ${SIGNKEY} steamfork.db.tar.gz *zst
